import tools.AssemblyCodeGenerator;
import tools.IRGenerator;
import tools.LRParser;
import tools.LexicalAnalyzer;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.List;

public class CompilerUI {
    private JFrame frame;
    private JTextArea sourceCodeArea;
    private JTextArea resultArea;

    public void createAndShowGUI() {
        // 1. 创建主窗口
        frame = new JFrame("简易编译器展示");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setLayout(new BorderLayout());

        // 设置整体背景为浅灰色
        frame.getContentPane().setBackground(new Color(240, 240, 240));

        // 2. 创建顶部按钮面板（替换原来的标签）
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        topPanel.setBackground(new Color(240, 240, 240));

        // 添加示例1按钮
        JButton example1Button = new JButton("示例1");
        example1Button.addActionListener(e -> {
            sourceCodeArea.setText(
                    "int main() {\n" +
                            "    int a = 5;\n" +
                            "    int b = 10;\n" +
                            "    if (a < b) {\n" +
                            "        printf(a);\n" +
                            "    } else {\n" +
                            "        printf(b);\n" +
                            "    }\n" +
                            "}"
            );
        });




//        int main()
//        {
//            int a;
//            int b = 5;
//            a = b + 3 * (2 - 1);
//            if (a < b) {
//                printf(a);
//            } else {
//                printf(b);
//            }
//            while (a != b) {
//                a=b;
//            }
//        }
        // 添加示例2按钮
        JButton example2Button = new JButton("示例2");
        example2Button.addActionListener(e -> {
            sourceCodeArea.setText(
                    "int main() {\n" +
                            "    int x = 3;\n" +
                            "    int y = 7;\n" +
                            "    x=y+3*(2-1);\n"+
                            "    if(x<y){\n"+
                            "    printf(x);\n"+
                            "    }else{\n"+
                            "    printf(y);\n"+
                            "    }\n"+
                            "    while (x < y) {\n" +
                            "        x = x + 1;\n" +
                            "    }\n" +

                            "}"
            );
        });

        topPanel.add(example1Button);
        topPanel.add(example2Button);
        frame.add(topPanel, BorderLayout.NORTH);

        // 3. 创建中央分割面板
        JSplitPane centerPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        centerPanel.setDividerLocation(400);
        centerPanel.setBackground(new Color(240, 240, 240));

        // 3.1 左侧源代码区域
        sourceCodeArea = new JTextArea();
        sourceCodeArea.setBorder(BorderFactory.createTitledBorder("源代码区域"));
        sourceCodeArea.setBackground(Color.WHITE);
        JScrollPane leftScroll = new JScrollPane(sourceCodeArea);
        leftScroll.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        centerPanel.setLeftComponent(leftScroll);

        // 3.2 右侧结果区域
        resultArea = new JTextArea();
        resultArea.setBorder(BorderFactory.createTitledBorder("按键结果显示区域"));
        resultArea.setBackground(Color.WHITE);
        resultArea.setEditable(false);
        JScrollPane rightScroll = new JScrollPane(resultArea);
        rightScroll.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        centerPanel.setRightComponent(rightScroll);

        frame.add(centerPanel, BorderLayout.CENTER);

        // 4. 创建底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.setBackground(new Color(240, 240, 240));

        // 4.1 词法分析按钮
        JButton lexicalButton = new JButton("词法分析");
        lexicalButton.setPreferredSize(new Dimension(120, 30));
        lexicalButton.addActionListener(e -> analyzeLexical());
        buttonPanel.add(lexicalButton);

        // 4.2 语法分析按钮
        JButton syntaxButton = new JButton("语法分析");
        syntaxButton.setPreferredSize(new Dimension(120, 30));
        syntaxButton.addActionListener(e -> analyzeSyntax());
        buttonPanel.add(syntaxButton);

        // 4.3 中间代码生成按钮
        JButton intermediateButton = new JButton("中间代码生成");
        intermediateButton.setPreferredSize(new Dimension(120, 30));
        intermediateButton.addActionListener(e -> generateIntermediateCode());
        buttonPanel.add(intermediateButton);

        // 4.4 汇编代码生成按钮
        JButton assemblyButton = new JButton("汇编代码生成");
        assemblyButton.setPreferredSize(new Dimension(120, 30));
        assemblyButton.addActionListener(e -> generateAssemblyCode());
        buttonPanel.add(assemblyButton);

        frame.add(buttonPanel, BorderLayout.SOUTH);

        // 样式规定部分
        Font sourceCodeFont = new Font("Microsoft YaHei Mono", Font.PLAIN, 20);
        sourceCodeArea.setFont(sourceCodeFont);
        resultArea.setFont(sourceCodeFont);

        // 5. 显示窗口
        frame.setVisible(true);
    }

    // 词法分析函数
    private void analyzeLexical() {
        String sourceCode = sourceCodeArea.getText();
        String mainbody = makesourceCode(sourceCode);
        LexicalAnalyzer lexicalAnalyzer = new LexicalAnalyzer();
        List<LexicalAnalyzer.Token> tokens = lexicalAnalyzer.analyze(mainbody);

        StringBuilder resultBuilder = new StringBuilder("词法分析结果:\n");
        for (LexicalAnalyzer.Token token : tokens) {
            resultBuilder.append(token.toString()).append("\n");
        }
        resultArea.setText(String.valueOf(resultBuilder));
    }

    private String makesourceCode(String sourceCode) {
        int count = 0;
        int start = 0;
        int end = sourceCode.length() - 1;

        while (count < 10) {
            if (sourceCode.charAt(start) != '\n' && sourceCode.charAt(start) != ' ') {
                count++;
            }
            start++;
        }
        return sourceCode.substring(start, end);
    }

    // 语法分析函数
    private void analyzeSyntax() {
        String sourceCode = sourceCodeArea.getText();
        String mainbody = makesourceCode(sourceCode);
        LexicalAnalyzer lexicalAnalyzer = new LexicalAnalyzer();
        List<LexicalAnalyzer.Token> tokens = lexicalAnalyzer.analyze(mainbody);

        LRParser parser = new LRParser(tokens);
        LRParser.Node astRoot = null;
        String result;
        try {
            astRoot = parser.parse();
            result = "语法分析结果:\n" + astRoot.show(0);
        } catch (Exception e) {
            result = "解析错误: " + e.getMessage();
        }
        resultArea.setText(result);
    }

    // 中间代码生成函数
    private void generateIntermediateCode() {
        String sourceCode = sourceCodeArea.getText();
        String mainbody = makesourceCode(sourceCode);
        LexicalAnalyzer lexicalAnalyzer = new LexicalAnalyzer();

        String result;
        try {
            List<LexicalAnalyzer.Token> tokens = lexicalAnalyzer.analyze(mainbody);
            LRParser parser = new LRParser(tokens);
            LRParser.Node astRoot = parser.parse();
            IRGenerator irGenerator = new IRGenerator();
            List<String> ircodes = irGenerator.generate(astRoot);
            result = "中间代码生成结果:\n";
            for (String ircode : ircodes) {
                result = result + ircode + '\n';
            }
        } catch (Exception e) {
            result = "生成失败: " + e.getMessage();
        }
        resultArea.setText(result);
    }

    // 汇编代码生成函数
    private void generateAssemblyCode() {
        String sourceCode = sourceCodeArea.getText();
        String mainbody = makesourceCode(sourceCode);
        LexicalAnalyzer lexicalAnalyzer = new LexicalAnalyzer();
        IRGenerator irGenerator = new IRGenerator();
        AssemblyCodeGenerator tacToAssemblyCodeGenerator = new AssemblyCodeGenerator();

        String result;
        try {
            List<LexicalAnalyzer.Token> tokens = lexicalAnalyzer.analyze(mainbody);
            LRParser parser = new LRParser(tokens);
            LRParser.Node astRoot = parser.parse();
            List<String> ircodes = irGenerator.generate(astRoot);
            String asm = tacToAssemblyCodeGenerator.generate(ircodes);
            result = ";汇编代码生成结果:\n" + asm;
        } catch (Exception e) {
            result = "生成失败: " + e.getMessage();
        }
        resultArea.setText(result);
    }
}